package com.lagou.edu.course.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lagou.edu.common.constant.MQConstant;
import com.lagou.edu.common.mq.RocketMqService;
import com.lagou.edu.common.mq.dto.BaseMqDTO;
import com.lagou.edu.course.api.CourseRemoteService;
import com.lagou.edu.course.api.dto.CourseDTO;
import com.lagou.edu.course.api.param.CourseQueryParam;
import com.lagou.edu.message.api.dto.CourseStatusReleaseDTO;
import com.lagou.edu.response.ResponseDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

@RestController
@RequestMapping("/course")
public class CourseController {

    @Autowired
    private CourseRemoteService courseRemoteService;
    @Autowired
    private RocketMqService rocketMqService;
    
    @PostMapping("/saveOrUpdateCourse")
    public ResponseDTO saveOrUpdateCourse(@RequestBody CourseDTO courseDTO){
        boolean isRelease = false;
        //查看课程是否是上架
        if(courseDTO.getStatus() != null && courseDTO.getStatus().equals(1)) {  //课程上架
            isRelease = true;
        }
        ResponseDTO responseDTO = courseRemoteService.saveOrUpdateCourse(courseDTO);
        /*if((1==responseDTO.getState()) && isRelease) {//发送消息通知
            rocketMqService.convertAndSend(MQConstant.Topic.COURSE_STATUS_RELEASE, new BaseMqDTO<CourseStatusReleaseDTO>(new CourseStatusReleaseDTO(courseDTO.getId()), UUID.randomUUID().toString()));
        }*/
        return responseDTO;
    }
    
    @GetMapping("/getCourseById")
    public ResponseDTO<CourseDTO> getCourseById(@RequestParam("courseId") Integer courseId)  {
        final CourseDTO courseDTO = courseRemoteService.getCourseById(courseId);
        return ResponseDTO.success(courseDTO);
    }
    
    @GetMapping("/changeState")
    public ResponseDTO changeState(@RequestParam("courseId") Integer courseId,
                                @RequestParam("status") Integer status)  {
        boolean isRelease = false;
        //查看课程是否是上架
        if(courseId != null && status == 1) {  //课程上架
            isRelease = true;
        }
        ResponseDTO responseDTO = courseRemoteService.updateCourseStatusById(courseId, status);
        if((1==responseDTO.getState()) && isRelease) {//发送消息通知
            rocketMqService.convertAndSend(MQConstant.Topic.COURSE_STATUS_RELEASE, new BaseMqDTO<CourseStatusReleaseDTO>(new CourseStatusReleaseDTO(courseId), UUID.randomUUID().toString()));
        }
        return responseDTO;
    }

    @PostMapping("/getQueryCourses")
    public ResponseDTO getQueryCourses(@RequestBody CourseQueryParam courseQueryParam)  {
        final Page<CourseDTO> queryCourses = courseRemoteService.getQueryCourses(courseQueryParam);
        return ResponseDTO.success(queryCourses);
    }


}
